import * as React from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { useAuth } from '@/providers/auth-provider'
import { X } from 'lucide-react'

interface LoginModalProps {
    open: boolean
    onClose: () => void
}

type ModalMode = 'login' | 'register'

export function LoginModal({ open, onClose }: LoginModalProps) {
    const { login, register, isLoading } = useAuth()
    const [mode, setMode] = React.useState<ModalMode>('login')
    const [phone, setPhone] = React.useState('')
    const [password, setPassword] = React.useState('')
    const [confirmPassword, setConfirmPassword] = React.useState('')
    const [name, setName] = React.useState('')
    const [error, setError] = React.useState<string | null>(null)

    React.useEffect(() => {
        if (open) {
            // 重置表单状态
            setMode('login')
            setPhone('')
            setPassword('')
            setConfirmPassword('')
            setName('')
            setError(null)
        }
    }, [open])

    const onSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        setError(null)
        
        try {
            if (mode === 'login') {
                await login({ phone, password })
            } else {
                if (password !== confirmPassword) {
                    setError('两次输入的密码不一致')
                    return
                }
                await register({ name, phone, password, password_confirmation: confirmPassword })
            }
            // 成功后关闭模态框
            onClose()
        } catch (err: any) {
            setError(err?.message ?? (mode === 'login' ? '登录失败' : '注册失败'))
        }
    }

    const handleBackdropClick = (e: React.MouseEvent) => {
        if (e.target === e.currentTarget) {
            onClose()
        }
    }

    if (!open) return null

    return (
        <div 
            className="fixed inset-0 z-[100] bg-black/50 backdrop-blur-sm flex items-center justify-center p-4"
            onClick={handleBackdropClick}
        >
            <Card className="w-full max-w-md md:max-w-lg bg-white shadow-2xl border-0 relative">
                <Button
                    variant="ghost"
                    size="icon"
                    className="absolute right-2 top-2 h-8 w-8"
                    onClick={onClose}
                >
                    <X className="h-4 w-4" />
                </Button>
                <CardHeader>
                    <CardTitle>{mode === 'login' ? '登录' : '注册'}</CardTitle>
                    <CardDescription>
                        {mode === 'login' ? '输入手机号和密码登录系统' : '创建新账户'}
                    </CardDescription>
                </CardHeader>
                <CardContent>
                    <form className="space-y-4" onSubmit={onSubmit}>
                        {mode === 'register' && (
                            <div className="space-y-1">
                                <label className="text-sm">姓名</label>
                                <Input 
                                    value={name} 
                                    onChange={(e) => setName(e.target.value)} 
                                    required 
                                    autoFocus={mode === 'register'}
                                    placeholder="请输入姓名"
                                />
                            </div>
                        )}
                        <div className="space-y-1">
                            <label className="text-sm">手机号</label>
                            <Input 
                                type="tel"
                                value={phone} 
                                onChange={(e) => setPhone(e.target.value)} 
                                required 
                                autoFocus={mode === 'login'}
                                placeholder="请输入手机号"
                            />
                        </div>
                        <div className="space-y-1">
                            <label className="text-sm">密码</label>
                            <Input 
                                type="password" 
                                value={password} 
                                onChange={(e) => setPassword(e.target.value)} 
                                required 
                                placeholder="请输入密码"
                            />
                        </div>
                        {mode === 'register' && (
                            <div className="space-y-1">
                                <label className="text-sm">确认密码</label>
                                <Input 
                                    type="password" 
                                    value={confirmPassword} 
                                    onChange={(e) => setConfirmPassword(e.target.value)} 
                                    required 
                                    placeholder="请再次输入密码"
                                />
                            </div>
                        )}
                        {error ? <p className="text-sm text-destructive">{error}</p> : null}
                        <Button className="w-full h-10" disabled={isLoading}>
                            {isLoading ? (mode === 'login' ? '登录中...' : '注册中...') : (mode === 'login' ? '登录' : '注册')}
                        </Button>
                        <div className="text-center">
                            <Button 
                                type="button"
                                variant="link" 
                                onClick={() => setMode(mode === 'login' ? 'register' : 'login')}
                                className="text-sm"
                            >
                                {mode === 'login' ? '没有账户？点击注册' : '已有账户？点击登录'}
                            </Button>
                        </div>
                    </form>
                </CardContent>
            </Card>
        </div>
    )
}
